<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/20/020
 * Time: 15:13
 */

namespace app\api\model;


use think\Exception;

class Product extends BaseModel {

    /**
     * 关联分类
     * @return \think\model\relation\BelongsTo
     */
    public function cate() {
        return $this->belongsTo('Category');
    }

    /**
     * 关联品牌
     * @return \think\model\relation\BelongsTo
     */
    public function brand() {
        return $this->belongsTo('Brand');
    }

    /**
     * 关联活动
     * @return \think\model\relation\BelongsTo
     */
    public function activity() {
        $time = time();
        return $this->belongsTo('ActivityProduct')->where('start_time', '<', $time)->where('end_time', '>', $time);
    }

    /**
     * 关联图片表，获取产品主图列表
     * @return $this
     */
    public function listImage() {
        return $this->hasMany('ProductImage')->where('type', '=', 1)->order('sort asc');
    }

    /**
     * 关联图片表，获取产品详情图列表
     * @return $this
     */
    public function contentImage() {
        return $this->hasMany('ProductImage')->where('type', '=', 2)->order('sort asc');
    }

    /**
     * 获取产品列表
     * @param array $where
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($where = []) {
        return self::with(['cate', 'brand', 'activity'])->where($where)
            ->order('id desc')
            ->paginate(input('param.limit', 15), false, ['query' => input('param.')]);
    }

    /**
     * 创建或者编辑产品
     * @param $param
     * @param $id
     * @return array|\think\response\Json
     */
    public static function createOrUpdateProduct($param, $id) {

        try {
            if ($id > 0) {

                $product = self::get($id);
                if (!$product) {
                    return json(['code' => 1, 'msg' => '产品不存在']);
                }

                $check_name = self::where([['name', 'eq', $param['name']], ['id', 'neq', $id]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '产品名称已存在!'];
                }

                $product->save($param);

            } else {
                $check_name = self::where([['name', 'eq', $param['name']]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '产品名称已存在!'];
                }

                self::create($param);
            }
            return ['code' => 0, 'msg' => '保存成功'];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }
}